﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Structs;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a file folder.
    /// </summary>
    public class CreateFileFolder : CreateAuditable<FileFolderEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("FILESYS");
            }
        }

        /// <summary>
        /// Gets or sets the parent folder identifier.
        /// </summary>
        public int ParentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public FileFolderFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out FileFolderEntity result)
        {
            base.Work(uow, out result);
            if(result.Parent != null)
            {
                uow.Execute(new UpdateFileFolderStats
                {
                    EntityID = result.Parent.EntityID
                });
            }
        }

        protected override void Construct(IUnitOfWork uow, FileFolderEntity entity)
        {
            base.Construct(uow, entity);

            entity.Parent = ParentID != 0
                ? uow.Execute(new GetFileFolder
                {
                    ThrowsException = true,
                    EntityID = ParentID
                }).Result
                : null;
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates a file folder.
    /// </summary>
    public class UpdateFileFolder : UpdateAuditable<FileFolderEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("FILESYS");
            }
        }

        /// <summary>
        /// Gets or sets the parent folder identifier.
        /// </summary>
        public int ParentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public FileFolderFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out FileFolderEntity result)
        {
            var oldParent = uow.Execute(new GetFileFolder
            {
                EntityID = EntityID
            }).Result.Parent;

            base.Work(uow, out result);

            if(result.Parent != null)
            {
                uow.Execute(new UpdateFileFolderStats
                {
                    EntityID = result.Parent.EntityID
                });
            }
            if(oldParent != null && !oldParent.Equals(result.Parent))
            {
                uow.Execute(new UpdateFileFolderStats
                {
                    EntityID = oldParent.EntityID
                });
            }
        }

        protected override void Revise(IUnitOfWork uow, FileFolderEntity entity)
        {
            base.Revise(uow, entity);

            entity.Parent = ParentID != 0
                ? uow.Execute(new GetFileFolder
                {
                    ThrowsException = true,
                    EntityID = ParentID
                }).Result
                : null;
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates a file folder statistics.
    /// </summary>
    public class UpdateFileFolderStats : OperateEntityByID<FileFolderEntity>
    {
        #region Utilities

        protected override void Work(IUnitOfWork uow, out FileFolderEntity result)
        {
            var folder = uow.Execute(new GetFileFolder
            {
                ThrowsException = true,
                EntityID = EntityID
            }).Result;

            uow.Flush();
            uow.SqlQuery("exec fwk_FileFolders_UpdateStats @FolderID=:FolderID, @UpdatedOn=:UpdatedOn")
                .SetInt32("FolderID", folder.EntityID)
                .SetDateTime("UpdatedOn", DateTime.UtcNow)
                .ExecuteUpdate();
            uow.Flush();

            result = uow.Execute(new RefreshEntity<FileFolderEntity>
            {
                Entity = folder
            }).Result;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the file folder.
    /// </summary>
    public class DeleteFileFolder : DeleteEntity<FileFolderEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("FILESYS");
            }
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow)
        {
            var parent = uow.Execute(new GetFileFolder
            {
                EntityID = EntityID
            }).Result.Parent;

            base.Work(uow);

            if(parent != null)
            {
                uow.Execute(new UpdateFileFolderStats
                {
                    EntityID = parent.EntityID
                });
            }
        }

        protected override void Destruct(IUnitOfWork uow, FileFolderEntity entity)
        {
            foreach(var i in entity.Childs)
            {
                uow.Execute(new DeleteFileFolder
                {
                    EntityID = i.EntityID
                });
            }
            foreach(var i in entity.Translations)
            {
                uow.Execute(new DeleteFileFolderTranslation
                {
                    EntityID = i.EntityID
                });
            }
            base.Destruct(uow, entity);
        }

        #endregion
    }

    /// <summary>
    /// Gets the file folder by identifier.
    /// </summary>
    public class GetFileFolder : GetEntity<FileFolderEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Translation__

    /// <summary>
    /// Creates a folder translation.
    /// </summary>
    public class CreateFileFolderTranslation : CreateTranslation
        <TFileFolderEntity, FileFolderEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("FILESYS");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Construct(IUnitOfWork uow, TFileFolderEntity entity)
        {
            base.Construct(uow, entity);

            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
        }

        #endregion
    }

    /// <summary>
    /// Updates the folder translation.
    /// </summary>
    public class UpdateFileFolderTranslation : UpdateTranslation
        <TFileFolderEntity, FileFolderEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("FILESYS");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Revise(IUnitOfWork uow, TFileFolderEntity entity)
        {
            base.Revise(uow, entity);

            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
        }

        #endregion
    }

    /// <summary>
    /// Saves a folder translation.
    /// </summary>
    public class SaveFileFolderTranslation : SaveTranslation
        <TFileFolderEntity, FileFolderEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("FILESYS");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out TFileFolderEntity result)
        {
            var translation = uow.Execute(new GetFileFolderTranslationByLanguage
            {
                HolderID = HolderID,
                LanguageID = LanguageID
            }).Result;
            if(translation == null)
            {
                translation = uow.Execute(new CreateFileFolderTranslation
                {
                    HolderID = HolderID,
                    LanguageID = LanguageID,
                    Name = Name
                }).Result;
            }
            else
            {
                translation = uow.Execute(new UpdateFileFolderTranslation
                {
                    EntityID = translation.EntityID,
                    LanguageID = LanguageID,
                    Name = Name
                }).Result;
            }
            result = translation;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the folder translation.
    /// </summary>
    public class DeleteFileFolderTranslation : DeleteTranlsation
        <TFileFolderEntity, FileFolderEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("FILESYS");
            }
        }

        #endregion
    }

    /// <summary>
    /// Gets the folder translation.
    /// </summary>
    public class GetFileFolderTranslation : GetTranlsation
        <TFileFolderEntity, FileFolderEntity>,
        IApiOperation
    {
    }

    /// <summary>
    /// Gets the folder translation.
    /// </summary>
    public class GetFileFolderTranslationByLanguage : GetTranlsationByLanguage
        <TFileFolderEntity, FileFolderEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over file folder collection.
    /// </summary>
    public class SearchFileFolders : SearchOperation<FileFolderEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchFileFolders()
        {
            Term = SearchTerm.Empty;
            SortDir = SortDirection.Ascending;
            SortBy = new []
            {
                FileFolderSortBy.ID
            };
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the search term.
        /// </summary>
        public SearchTerm Term
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the language identifier.
        /// </summary>
        public int? LanguageID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the parent folder identifier.
        /// </summary>
        public int? ParentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public FileFolderFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort by.
        /// </summary>
        public FileFolderSortBy[] SortBy
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<FileFolderEntity> Build(IUnitOfWork uow, IQueryable<FileFolderEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            switch(Term.Mode)
            {
                case SearchTerm.SearchMode.StartsWith:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Name.StartsWith(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.StartsWith(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.EndsWith:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Name.EndsWith(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.EndsWith(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.Contains:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Name.Contains(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.Contains(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.Equals:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Name.Equals(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.Equals(Term.Keyword)));
                    break;
                default:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i => i.Language.EntityID == LanguageID.Value));
                    break;
            }
            if(ParentID.HasValue)
                query = query.Where(x => x.ParentID == ParentID.Value);
            if(SortBy != null)
            {
                for(int i = 0; i < SortBy.Length; i++)
                {
                    switch(SortBy[i])
                    {
                        case FileFolderSortBy.Size:
                            query = query.OrderBy(x => x.Size, SortDir, i != 0);
                            break;
                        case FileFolderSortBy.FileCount:
                            query = query.OrderBy(x => x.FileCount, SortDir, i != 0);
                            break;
                        case FileFolderSortBy.CreatedOn:
                            query = query.OrderBy(x => x.CreatedOn, SortDir, i != 0);
                            break;
                        default:
                            query = query.OrderBy(x => x.EntityID, SortDir, i != 0);
                            break;
                    }
                }
            }
            return query;
        }

        #endregion
    }

    #endregion
}
